package cn.server.handler;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.server.conf.SQLParameter;
import cn.server.conf.SQLParameter.Type;
import cn.server.data.GridData;
import cn.server.util.SQLUtil;
import cn.server.util.ServerConfUtil;

import com.alibaba.fastjson.JSON;
import com.jfinal.core.Controller;

public class ManageControler extends Controller {
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(ManageControler.class);

	public final static String DEFAULT_JSON = "{\"total\":0,\"rows\":[]}";

	public void index() {
		render("/index.html");
	}

	public void preview() {
		String json = DEFAULT_JSON;
		try {
			// TODO 从数据库读取详细信息
			List<Map<String, Object>> result = SQLUtil.listQuery(null, ServerConfUtil.getSql("total"), -1, -1);
			if (result != null && !result.isEmpty()) {
				GridData data = new GridData();
				data.setRows(result);
				json = JSON.toJSONString(data);
			}
		} catch (Throwable e) {
			logger.error("error query data", e);
		}
		renderJson(json);
	}

	public void showDetail() {
		render("/detail.jsp");
	}

	public void detail() {
		String ip = getPara("ip");
		// TODO 处理数据库分页
		String json = DEFAULT_JSON;
		try {
			SQLParameter p = new SQLParameter("sourceip", ip, Type.EQUAL);
			GridData data = new GridData();
			data.setRows(SQLUtil.listQuery(Arrays.asList(p), ServerConfUtil.getSql("detail"), -1, -1));
			json = JSON.toJSONString(data);
		} catch (Throwable e) {
			logger.error("error query data", e);
		}
		renderJson(json);
	}
}
